﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;

namespace SpaceEngineersSaveEditor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            RunLogic();
        }

        private void RunLogic()
        {
            var saveFolder = GetSaveFolder();

            if (saveFolder != null)
            {
                PopulateWorldList(saveFolder);
                
            }
            else
            {
                throw new ApplicationException("saveFolder is null for some reason");
            }
        }

        private string GetSaveFolder()
        {
            var roamingFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var spaceEngineersSavesFolder = roamingFolder + Path.DirectorySeparatorChar + "SpaceEngineers" + Path.DirectorySeparatorChar + "Saves";
            var saveFolders = Directory.EnumerateDirectories(spaceEngineersSavesFolder);

            if (saveFolders.Count() != 1)
            {
                var errorMessage = string.Format("Must be only 1 save folder in: {0}", saveFolders);
                throw new ApplicationException(errorMessage);
            }

            foreach (var saveFolder in saveFolders)
            {
                return saveFolder;
            }

            return null;
        }

        private void PopulateWorldList(string saveFolder)
        {
            var worldFolders = Directory.EnumerateDirectories(saveFolder);
            WorldList = new ObservableWorldCollection(worldFolders);
            DataContext = this;

            foreach (var world in WorldList)
            {
                Console.WriteLine(world.WorldName);
            }
        }

        public ObservableWorldCollection WorldList { get; set; }

        private void ListBoxWorlds_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedItem = ListBoxWorlds.SelectedItem;

            ButtonEditWorld.IsEnabled = (selectedItem != null);
        }

        private void ButtonEditWorld_Click(object sender, RoutedEventArgs e)
        {
            var world = (World)ListBoxWorlds.SelectedItem;
            var objectsWindow = new ObjectsWindow(world);
            objectsWindow.Show();
        }
    }
}
